package com.ydd.controller.admin;

import com.ydd.constant.JwtClaimsConstant;
import com.ydd.constant.MessageConstant;
import com.ydd.context.BaseStringContext;
import com.ydd.dto.LoginAndRegDTO;
import com.ydd.entity.SysUser;
import com.ydd.exception.LoginFailedException;
import com.ydd.properties.JwtProperties;
import com.ydd.result.Result;
import com.ydd.service.AdminIndexService;
import com.ydd.utils.JwtUtil;
import com.ydd.vo.IndexBaseInfoVO;
import com.ydd.vo.IndexGetConfigVO;
import com.ydd.vo.IndexProfileVO;
import com.ydd.vo.TokenVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO
 * @Author fang
 * @Date 2023-05-29 16:41
 */
@Api(tags = "管理端-基础模块")
@RestController
@RequestMapping("/admin/index")
@Slf4j
public class AdminIndexController {
    @Autowired
    AdminIndexService adminIndexService;
    @Autowired
    JwtProperties jwtProperties;

    @ApiOperation("基础模块-主页统计信息")
    @GetMapping("/baseInfo")
    public Result<IndexBaseInfoVO> baseInfo() {
        log.info("基础模块-主页统计信息");
        return Result.success(adminIndexService.baseInfo());
    }

    @ApiOperation("基础模块-获取用户资料")
    @PostMapping("/profile")
    public Result<IndexProfileVO> profile(){
        log.info("基础模块-获取用户资料");
        return Result.success(adminIndexService.profile());
    }

    @ApiOperation("获取系统配置")
    @GetMapping("/getConfig")
    public Result<IndexGetConfigVO> getConfig(){
        IndexGetConfigVO configVO=adminIndexService.getConfig();
        System.out.println(configVO);
        return Result.success(configVO);
    }

    @ApiOperation("管理端登录接口")
    @PostMapping("/login")
    public Result sysLogin(@RequestBody LoginAndRegDTO loginAndRegDTO){
        log.info("管理端用户接口：{}",loginAndRegDTO);
        SysUser sysUser = adminIndexService.findByCondition(loginAndRegDTO);
        String token;
        if(sysUser!=null){
            String sysUserId = sysUser.getId();
            Map<String,Object> map = new HashMap<>();
            map.put(JwtClaimsConstant.ADMIN_ID,sysUserId);
            token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), map);
            BaseStringContext.setCurrentId(sysUserId);
        }else{
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        return Result.success(new TokenVO(token));
    }
}
